<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace addons\news\user\controller;


/**
 * Description of News
 * 文章
 * @author
 */
class News extends \web\user\controller\AddonUserBase {


    public function index() {
        return $this->fetch();
    }

    /**
     * 文章列表
     * @return array
     */
    public function loadList() {
        $keyword = $this->_get('keyword');
        $is_show = $this->_get('is_show');
        $filter = ' 1=1';
        if ($keyword != null) {
            $filter .= ' and title like \'%' . $keyword . '%\'';
        }
        $order = 'id desc';
        if ($is_show != null) {
            $filter .= ' and is_show = ' . $is_show;
        }
        $m = new \addons\news\model\News();
        $total = $m->getTotal($filter);
        $fields = ' * ';
        $rows = $m->getDataList($this->getPageIndex(), $this->getPageSize(), $filter, $fields, $order);
        return $this->toDataGrid($total, $rows);
    }

    /**
     * 文章添加和修改
     * @return array|mixed|string
     */
    public function news_post() {
        if (IS_POST) {
            $data = $_POST;
            $id = $data['id'];
            $data['about_ids'] = '';
            if ($data['news_json']) {
                $new_id_arr = json_decode($data['news_json']);
                $idArr = array_column($new_id_arr, 'id');
                $data['about_ids'] = implode(",", $idArr);
            }
            $data['update_time'] = NOW_DATETIME;
            $data['is_allow'] = 1;
            $data['content'] = htmlspecialchars_decode($data['content']);
            $status = 0;
            if (isset($data['is_audio'])) {
                if ($data['is_audio'] == 1) {
                    if (!preg_match('/(http:\/\/)|(https:\/\/)/i', $data['mp3_url'])) {
                        return $this->failData('音频地址不正确');
                    }
                    $data['is_video'] = 0;
                    $data['video_url'] = 0;
                    $status = 1;
                }
            }
            if (isset($data['is_video'])) {
                if ($data['is_video'] == 1) {
                    if (!preg_match('/(http:\/\/)|(https:\/\/)/i', $data['video_url'])) {
                        return $this->failData('视频地址不正确');
                    }
                    $data['is_audio'] = 0;
                    $data['mp3_url'] = 0;
                    $status = 2;
                }
            }
//            if (isset($data['is_push'])) {
//                if ($data['is_push'] == 1) {
//                    $APush = new APush();
//                    $changetype = [];
//                    $changetype['type'] = 'news';
//                    $changetype['status'] = $status;
//                    $changetype['id'] = $id;
//                    $res = $APush::push_all($data['title'], null, $changetype);
//                    if (!$res) {
//                        return $this->failData('推送失败');
//                    }
//                }
//            }
            $m = new \addons\news\model\News();
            try {
                if (empty($id)) {
                    unset($data['id']);
                    $data['create_time'] = NOW_DATETIME;
                    $ret = $m->add($data, false);
                } else {
                    $where['id'] = $id;
                    $ret = $m->save($data, $where, null, false);
                }

                //添加管理日志
                $this->addLog(self::LOG_EDIT, 'News', $data, 0, '商学院');
                return $this->successData();
            } catch (\Exception $e) {
                return $this->failData($e->getMessage());
            }
        } else {
            $id = $this->_get('id');
            $this->assign('id', $id);
            $this->setLoadDataAction('loadData');
            return $this->fetch();
        }
    }

    public function play(){
        $this->assign('path', $this->_get('path'));
        return $this->fetch();
    }

    /**
     * 审核文章
     */
    public function newsExamine() {
        $user_type = $this->user_type;
        if ($user_type != 0) {
            return $this->failData('无权限');
        }
        $id = intval($this->_get('id'));
        $type = $this->_get('type');
        if (!empty($id)) {
            $m = new \addons\news\model\News();
            $m->startTrans();
            try {
                if ($type == 1) {
                    $data['is_allow'] = 1;
                } else {
                    $data['is_allow'] = 2;
                }
                $res = $m->where(['id' => $id])->update($data);
                
                $m->commit();
                return $this->successData();
            } catch (\Exception $e) {
                $m->rollback();
                return $this->failData($e->getMessage());
            }
        } else {
            return $this->failData('审核失败，参数有误');
        }
    }

    /**
     * 爬虫
     */
    public function crawlerDoc() {
        $type = $this->user_type;
        if ($type != 0) {
            return $this->failData('权限不够');
        }
        if (IS_POST) {
            $m = new \addons\config\model\Crawler();
            $info = $_POST;
            //爬取新闻
            $data = $m->CrawlerNewsApi();
            if (empty($data)) {
                return $this->failData('无数据');
            }
            //添加到爬虫列表，获取爬虫数组
            $data = $m->addNews($data);
            if (!$data) {
                return $this->failData('已是最新爬虫');
            }
            $add = [];
            //转换成新闻字段
            foreach ($data as $k => $v) {
                $tmp = [];
                $tmp['category_id'] = $info['category_id'];
                $tmp['author_type'] = 2;
                $tmp['remaining_of_drill'] = $info['of_drill'];
                $tmp['of_drill'] = $info['of_drill'];
                $tmp['title'] = $v['title'];
                $tmp['desc'] = $v['desc'];
                $tmp['content'] = $v['content'];
                $tmp['keywords'] = $v['keywords'];
                $tmp['update_time'] = NOW_DATETIME;
                $tmp['create_time'] = $v['create_at'];
                $tmp['pen_name'] = $v['author'];
                $tmp['author_name'] = $v['pan_name'];
                $tmp['images'] = $v['head_img'];
                $add[] = $tmp;
            }
            $news = new \addons\news\model\News();
            $res = $news->saveAll($add);
            if ($res) {
                return $this->successData('爬虫成功');
            } else {
                return $this->failData('爬虫失败');
            }
        } else {
            $id = $this->_get('id');
            $this->assign('id', $id);
            $categoryM = new \addons\news\model\NewsCategory();
            $category_data = $categoryM->getDataList(); //新闻资讯分类目录
            $this->assign('category_data', json_encode($category_data));
            $this->setLoadDataAction('loadData');
            return $this->fetch();
        }
    }

    public function loadData() {
        $id = $this->_get('id');
        $m = new \addons\news\model\News();
        $data = $m->getDetail($id);
        $data['content'] = htmlspecialchars_decode($data['content']);
        return $data;
    }

    /**
     * 删除
     */
    public function del() {
        $id = intval($this->_get('id'));
        if (!empty($id)) {
            $m = new \addons\news\model\News();
            try {
                $res = $m->deleteData($id);
                if ($res > 0) {
                    //添加管理日志
                    $this->addLog(self::LOG_EDIT, 'News', [], 0, '商学院删除');
                    return $this->successData();
                } else {
                    return $this->failData('删除失败');
                }
            } catch (\Exception $e) {
                return $this->failData($e->getMessage());
            }
        } else {
            return $this->failData('删除失败，参数有误');
        }
    }

    /**
     * 选择文章
     * @return type
     */
    public function select_news() {
        $singleSelect = $this->_get('singleSelect')?1:0;
        // $singleSelect = 0;
        $this->assign('singleSelect', $singleSelect);
        $filter_ids = $this->_get('filter_ids');
        $this->assign('filter_ids', $filter_ids);
        return $this->fetch();
    }

    /**
     * 加载选择商品
     */
    public function loadNews() {
        $filter_ids = $this->_get('filter_ids'); //过滤IDS
//        dump($filter_ids);exit;
        $keyword = $this->_get('keyword');
//        $class_id = $this->_get('class_id');
        $filter = 'is_public = 1';
        if (!empty($filter_ids)) {
            $filter .= ' and id not in(' . $filter_ids . ')';
        }
        if (!empty($class_id))
            $filter .= ' and class_id=' . $class_id;
        if ($keyword != null) {
            $filter .= ' and title like \'%' . $keyword . '%\'';
        }
        $m = new \addons\news\model\News();
        $rows = $m->getDataList(-1, -1, $filter, 'id,title');
        $total = count($rows);
        return $this->toDataGrid($total, $rows);
    }

    //店铺筛选列表
    public function news_user(){
        return $this->fetch();
    }
    public function newsLoadSelectUser(){
        $keyword = $this->_get('keyword');
        $filter = ' is_allow = 0';
        if ($keyword != null) {
            $filter .= ' and title like \'%' . $keyword . '%\'';
        }
        $m = new \addons\news\model\News();
        $total = $m->getTotal($filter);
        $rows = $m->getDataList($this->getPageIndex(), $this->getPageSize(), $filter);
        return $this->toDataGrid($total, $rows);
    }

}
